package com.zys.el.time.ws;

import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zys.el.time.constants.RedisConstants;
import com.zys.el.time.ws.constants.WSModeCode;
import com.zys.el.time.ws.service.IChatService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 话题聊天
 */
@Component
@Slf4j
@ServerEndpoint(value = "/ws/{roomId}/{userId}")
public class WebSocketServer {

    public static StringRedisTemplate stringRedisTemplate;

    public static IChatService chatService;

    // concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象
    private static final ConcurrentHashMap<String, Set<WebSocketServer>> topicSocketMap =
            new ConcurrentHashMap<>();

    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    // 接收userId
    private String userId;


    /**
     * 初始拉取消息记录条数
     */
    private final static int initMaxCount = 10;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("roomId") String roomId, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;

        if (topicSocketMap.containsKey(roomId)) {
            Set<WebSocketServer> set = topicSocketMap.get(roomId);
            set.add(this);
        } else {
            HashSet<WebSocketServer> set = new HashSet<>();
            set.add(this);
            topicSocketMap.put(roomId, set);
        }

        log.debug("房间{}的用户{}连接，当前在线人数为:{}", roomId, userId, getOnlineCount(roomId));

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("roomId") String roomId) {
        topicSocketMap.get(roomId).remove(this);
        log.info("房间{}的用户{}退出, 当前在线人数为:{}", roomId, userId, getOnlineCount(roomId));
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(@PathParam("roomId") String roomId, String message, Session session) {
        log.info("用户消息:" + userId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (StringUtils.isNotBlank(message)) {
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                String data = jsonObject.getString("data");
                String ModeCode = jsonObject.getString("ModeCode");

                switch (ModeCode) {
                    case WSModeCode.BATCH_SEND:
                        log.debug("------群发------");
                        // 存入redis
                        String key = RedisConstants.ROOM_KEY + roomId;
                        JSONObject msgData = JSON.parseObject(data);
                        msgData.put("roomId", roomId);
                        chatService.save(key, msgData);
                        // 群发
                        this.BatchSend(message, roomId);
                        break;
                    case WSModeCode.HISTORY:
                        log.debug("------获取历史记录------");
                        this.sendHistoryMsg(roomId);
                        break;
                    case WSModeCode.HEART_BEAT:
                        log.debug("心跳检测: " + data);
                        this.sendMessage(message);
                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session ws会话
     * @param error   异常
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:{}, 原因:{}", this.userId, error.getMessage());
        error.printStackTrace();
    }


    /**
     * 发送历史记录
     *
     * @param roomId 房间号
     */
    public void sendHistoryMsg(String roomId) {
        // 读取历史消息记录
        String key = RedisConstants.ROOM_KEY + roomId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, System.currentTimeMillis(), 0, initMaxCount);

        // 取出消息记录并传回
        if (typedTuples != null && !typedTuples.isEmpty()) {
            ArrayList<String> list = new ArrayList<>();
            for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
                long score = Objects.requireNonNull(tuple.getScore()).longValue();
                String msg = tuple.getValue();
                JSONObject jsonObject = JSONObject.parseObject(msg);
                assert jsonObject != null;
                jsonObject.put("time", score);
                msg = jsonObject.toString();
                if (StringUtils.isNotEmpty(msg))
                    list.add(msg);
            }
            Map<String, Object> map = MapBuilder.<String, Object>create()
                    .put("ModeCode", WSModeCode.HISTORY)
                    .put("data", list).build();
            String jsonMap = JSON.toJSONString(map);
            // 传回历史聊天数据
            sendMessage(jsonMap);
        }
    }

    /**
     * 群发
     *
     * @param msgData 群发消息
     * @param roomId  房间号
     */
    public void BatchSend(String msgData, String roomId) {
        // 群发
        Set<WebSocketServer> set = topicSocketMap.get(roomId);
        HashSet<WebSocketServer> s = new HashSet<>(set);
        s.remove(this);
        this.sendInfo(msgData, roomId, s);
    }

    /**
     * 服务端主动推送
     */
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送自定义消息
     **/
    public void sendInfo(String message, String roomId, Set<WebSocketServer> s) {
        for (WebSocketServer webSocketServer : s) {
            webSocketServer.sendMessage(message);
        }
        log.debug("发送消息到：{}，报文:{}", roomId, message);
    }

    /**
     * 获得此时的在线人数
     *
     * @return 在线人数
     */
    public static int getOnlineCount(String roomId) {
        return topicSocketMap.get(roomId).size();
    }

}